package field

import "gitee.com/yanwc/ebicycle/device/utils"

type (
	TLVType [1]byte
	TLVLen  [1]byte
)

// TLV 扩展字段
type TLV struct {
	TlvType  TLVType
	TlvLen   TLVLen
	TLVValue []byte
}

// TLV解包
func UnWrapTlvPacket(data []byte) []TLV {
	var rev []TLV
	startIndex := 0
	endIndex := 2
	for {
		if endIndex >= len(data) {
			break
		}
		var tlvType TLVType
		var tlvLen TLVLen

		utils.LoadPacket(data[startIndex:endIndex], tlvType[:], tlvLen[:])
		l := tlvLen.Uint8()
		if l > 0 {
			startIndex = endIndex
			endIndex = startIndex + int(tlvLen.Uint8())
			tlvValue := make([]byte, l)
			utils.LoadPacket(data[startIndex:endIndex], tlvValue[:])
			rev = append(rev, TLV{
				TlvType:  tlvType,
				TlvLen:   tlvLen,
				TLVValue: tlvValue,
			})
		}
		startIndex = endIndex
		endIndex = startIndex + 2
	}

	return rev
}
